package com.guomao.demo;

import com.guomao.utils.JwtUtils;

import java.util.HashMap;

public class JwtDemo {

    public static class AuthService {

        public String login(String username, String password) {
            if ("admin".equals(username) && "admin".equals(password)) {
//                JwtUtils.generateToken()
                HashMap<String, Object> map = new HashMap<>();

                map.put("username", username);
                map.put("id", 1);
                map.put("role", "administrator");

                return JwtUtils.generateToken(username, map);
            }
            throw new RuntimeException("用户名或密码错误");
        }

        public boolean validateToken(String token) {
            return JwtUtils.validateToken(token);
        }

        public String getUsernameFromToken(String token) {
            return JwtUtils.getSubjectFromToken(token);
        }
    }


    public static class APIGateway {

        private static AuthService authService = new AuthService();

        public void handleRequest(String token, String path) {
            System.out.println("请求资源路径:" + path);

            if (!authService.validateToken(token)) {
                System.out.println("验证失败,令牌无效!");
                return;
            }

            String username = authService.getUsernameFromToken(token);
            System.out.println("验证成功:账户信息" + username);
        }

    }

    public static void main(String[] args) {

        AuthService service = new AuthService();

        String token = service.login("admin", "admin");
        System.out.println("登录成功,获取到令牌:" + token);

        APIGateway gateway = new APIGateway();

        gateway.handleRequest(token, "/api/admin");

        gateway.handleRequest("abc.xyz,123", "/api/users");




    }
}
